<script setup lang="ts">
import type { OtherReceivedAcceptanceBill } from '@/api/types/finance'
import type { InfoItem } from '@/components/DetailCard.vue'
import { onPullDownRefresh, onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getOtherReceivedAcceptanceBillById } from '@/api/finance'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import DetailCard from '@/components/DetailCard.vue'
import { getStatusName } from '@/constants/enums'
import { useFlow } from '@/hooks/useFlow'

// 定义页面配置
definePage({
  style: {
    navigationBarTitleText: '外收承兑汇票详情',
    enablePullDownRefresh: true, // 启用下拉刷新
  },
})

const id = ref('')
const flowId = ref('')
const flowIdValue = ref('')
const idValue = ref('')
// 使用流程相关功能
const { currentProcess, getProcessInstance, getCurrentUserPendingTaskId, loading } = useFlow()

// 业务详情数据
const businessData = ref<OtherReceivedAcceptanceBill | null>(null)
const errorMessage = ref('')

// 刷新状态
const refreshing = ref(false)

// 数据加载状态管理
const isDataLoaded = ref(false) // 标记数据是否已加载
const isInitialLoad = ref(true) // 标记是否是首次加载

// 获取业务详情数据
async function getBusinessData() {
  try {
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }
    // 等待流程实例数据加载完成并获取businessKey
    if (!currentProcess.value.businessKey) {
      console.log('等待流程实例数据加载...')
      // 等待一段时间让流程数据加载完成
      await new Promise(resolve => setTimeout(resolve, 100))

      if (!currentProcess.value.businessKey) {
        throw new Error('业务ID不存在，请确保流程实例数据已加载')
      }
    }

    console.log('获取业务数据，businessKey:', currentProcess.value.businessKey)
    const res = await getOtherReceivedAcceptanceBillById(currentProcess.value.businessKey)
    businessData.value = res.data || null
    console.log('业务数据获取成功:', res)

    // 标记数据已加载
    isDataLoaded.value = true
  }
  catch (error) {
    console.error('获取业务详情失败:', error)
    errorMessage.value = '获取业务详情失败，请重试'
    // 使用默认数据防止页面崩溃
    businessData.value = {
      id: id.value,
      createTime: '-',
      businessInstitutionName: '-',
      businessDepartmentName: '-',
      salesmanName: '-',
      preparer: '-',
      bizNo: '-',
      billType_dictText: '-',
      billNumber: '-',
      faceAmount: 0,
      billAmount: 0,
      issueDate: '-',
      maturityDate: '-',
      payee: '-',
      previousHolder: '-',
      drawer: '-',
      drawerBank: '-',
      drawerAccount: '-',
      acceptor: '-',
      acceptanceBank: '-',
      acceptorAccount: '-',
      receiptDate: '-',
      adjustmentDays: 0,
      discountDays: 0,
      annualDiscountDays: 0,
      annualDiscountRate: 0,
      discountFee: 0,
      associatedAmount: 0,
      remarks: '-',
      approvalStatus: 0,
      paymentStatus: 0,
      billStatus: 0,
      invoicingStatus: 0,
    }
    // 即使出错也标记为已加载，避免重复请求
    isDataLoaded.value = true
  }
}

// 重置数据加载状态
function resetDataLoadingState() {
  isDataLoaded.value = false
  isInitialLoad.value = true
}

// 下拉刷新处理函数
async function handlePullDownRefresh() {
  console.log('开始下拉刷新')
  refreshing.value = true

  try {
    // 强制重新加载：重置状态
    isDataLoaded.value = false
    isInitialLoad.value = true

    // 第一步：获取流程实例数据
    console.log('刷新 - 开始获取流程实例数据...')
    await getProcessInstance(id.value)
    console.log('刷新 - 流程实例数据获取完成:', currentProcess.value)

    // 第二步：基于流程实例数据获取业务数据
    console.log('刷新 - 开始获取业务数据...')
    await getBusinessData()
    console.log('刷新 - 业务数据获取完成')

    // 显示成功提示
    uni.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 2000,
    })
  }
  catch (error) {
    console.error('下拉刷新失败:', error)
    // 即使出错也要关闭加载状态
    refreshing.value = false
    uni.stopPullDownRefresh()

    uni.showToast({
      title: '刷新失败',
      icon: 'error',
      duration: 2000,
    })

    // 重新抛出错误，让 uni-app 的错误处理机制也能捕获到
    throw error
  }
  finally {
    // 再次确保状态被关闭
    refreshing.value = false
    uni.stopPullDownRefresh()
    console.log('下拉刷新状态已关闭')
  }
}

// 页面加载时获取数据
onLoad(async (e) => {
  if (e.id) {
    id.value = e.id
    flowId.value = e.flowId
    if (e.flowId) {
      flowIdValue.value = e.flowId
    }
    idValue.value = e.id || ''

    resetDataLoadingState() // 重置状态

    try {
      // 第一步：获取流程实例数据
      console.log('onLoad - 开始获取流程实例数据...')
      await getProcessInstance(e.id)
      console.log('onLoad - 流程实例数据获取完成:', currentProcess.value)

      // 第二步：基于流程实例数据获取业务数据
      console.log('onLoad - 开始获取业务数据...')
      await getBusinessData()
      console.log('onLoad - 业务数据获取完成')
    }
    catch (error) {
      console.error('页面数据加载失败:', error)
      uni.showToast({
        title: '数据加载失败',
        icon: 'error',
        duration: 2000,
      })
    }
  }
})

// 页面显示时刷新数据（避免重复请求）
onShow(async () => {
  if (id.value) {
    try {
      // 如果是首次加载，数据已经在 onLoad 中获取，onShow 不重复请求
      if (isInitialLoad.value) {
        console.log('onShow - 首次加载已在 onLoad 中完成，跳过重复请求')
        isInitialLoad.value = false // 标记首次加载完成
        return
      }

      // 如果数据已加载完成，onShow 不重复请求（除非需要强制刷新）
      if (isDataLoaded.value) {
        console.log('onShow - 数据已加载，跳过重复请求')
        return
      }

      // 只有在数据未加载时才执行
      console.log('onShow - 数据未加载，开始获取...')

      // 检查流程实例数据是否存在，如果不存在则先获取
      if (!currentProcess.value || !currentProcess.value.businessKey) {
        console.log('onShow - 流程实例数据不存在，重新获取...')
        await getProcessInstance(id.value)
      }

      // 然后获取业务数据
      await getBusinessData()
    }
    catch (error) {
      console.error('页面显示时数据加载失败:', error)
    }
  }
})

// 监听下拉刷新事件
onPullDownRefresh(handlePullDownRefresh)

// 获取状态显示文本
function getStatusText(type: string, value?: number) {
  const statusMaps: Record<string, Record<number, string>> = {
    approvalStatus: {
      0: '待审批',
      1: '审批中',
      2: '已审批',
      3: '已拒绝',
      4: '已撤销',
    },
    paymentStatus: {
      0: '待支付',
      1: '支付中',
      2: '已支付',
      3: '支付失败',
      4: '已退款',
    },
    billStatus: {
      0: '正常',
      1: '已承兑',
      2: '已贴现',
      3: '已转让',
      4: '已到期',
      5: '已兑付',
      6: '已作废',
    },
    invoicingStatus: {
      0: '未开票',
      1: '开票中',
      2: '已开票',
      3: '开票失败',
    },
    splitStatus: {
      0: '未拆分',
      1: '拆分中',
      2: '已拆分',
    },
    isInvoiced: {
      0: '否',
      1: '是',
    },
  }

  if (value === undefined || value === null) {
    return '-'
  }

  return statusMaps[type]?.[value] || `未知状态(${value})`
}

// 准备基本信息数据
const basicInfoList = computed<InfoItem[]>(() => [
  {
    label: '业务机构',
    value: businessData.value?.businessInstitutionName || '-',
    key: 'businessInstitutionName',
  },
  {
    label: '业务部门',
    value: businessData.value?.businessDepartmentName || '-',
    key: 'businessDepartmentName',
  },
  {
    label: '业务员',
    value: businessData.value?.salesmanName || '-',
    key: 'salesmanName',
  },
  {
    label: '业务日期',
    value: businessData.value?.businessDate || '-',
    key: 'businessDate',
  },
  {
    label: '制单人',
    value: businessData.value?.preparer || '-',
    key: 'preparer',
  },
  {
    label: '创建时间',
    value: businessData.value?.createTime || '-',
    key: 'createTime',
  },
  {
    label: '更新时间',
    value: businessData.value?.updateTime || '-',
    key: 'updateTime',
  },
])

// 准备汇票信息数据
const billInfoList = computed<InfoItem[]>(() => [
  {
    label: '业务编号',
    value: businessData.value?.bizNo || '-',
    key: 'bizNo',
  },
  {
    label: '票据类型',
    value: businessData.value?.billType_dictText || '-',
    key: 'billType_dictText',
  },
  {
    label: '票据号码',
    value: businessData.value?.billNumber || '-',
    key: 'billNumber',
  },
  {
    label: '原票据号码',
    value: businessData.value?.originalBillNumber || '-',
    key: 'originalBillNumber',
  },
  {
    label: '票面金额',
    value: businessData.value?.faceAmount ? `￥${businessData.value.faceAmount.toLocaleString()}` : '-',
    key: 'faceAmount',
  },
  {
    label: '票据金额',
    value: businessData.value?.billAmount ? `￥${businessData.value.billAmount.toLocaleString()}` : '-',
    key: 'billAmount',
  },
  {
    label: '出票日期',
    value: businessData.value?.issueDate || '-',
    key: 'issueDate',
  },
  {
    label: '到期日期',
    value: businessData.value?.maturityDate || '-',
    key: 'maturityDate',
  },
  {
    label: '收票日期',
    value: businessData.value?.receiptDate || '-',
    key: 'receiptDate',
  },
  {
    label: '出票人',
    value: businessData.value?.drawer || '-',
    key: 'drawer',
    forceMultiline: true,
  },
  {
    label: '出票人银行',
    value: businessData.value?.drawerBank || '-',
    key: 'drawerBank',
  },
  {
    label: '出票人账号',
    value: businessData.value?.drawerAccount || '-',
    key: 'drawerAccount',
  },
  // {
  //   label: '承兑人',
  //   value: businessData.value?.acceptor || '-',
  //   key: 'acceptor',
  // },
  // {
  //   label: '承兑银行',
  //   value: businessData.value?.acceptanceBank || '-',
  //   key: 'acceptanceBank',
  // },
  // {
  //   label: '承兑人账号',
  //   value: businessData.value?.acceptorAccount || '-',
  //   key: 'acceptorAccount',
  // },
  {
    label: '收票人',
    value: businessData.value?.payee || '-',
    key: 'payee',
  },
  {
    label: '背书单位',
    value: businessData.value?.previousHolder || '-',
    key: 'previousHolder',
    forceMultiline: true,
  },
  // {
  //   label: '原收款人',
  //   value: businessData.value?.originalPayee || '-',
  //   key: 'originalPayee',
  // },
  // {
  //   label: '原前手',
  //   value: businessData.value?.originalPreviousHolder || '-',
  //   key: 'originalPreviousHolder',
  // },
  // {
  //   label: '开票抬头',
  //   value: businessData.value?.invoicingTitle || '-',
  //   key: 'invoicingTitle',
  // },
  // {
  //   label: '税号',
  //   value: businessData.value?.taxNumber || '-',
  //   key: 'taxNumber',
  // },
  // {
  //   label: '开票金额',
  //   value: businessData.value?.invoicingAmount ? `￥${businessData.value.invoicingAmount.toLocaleString()}` : '-',
  //   key: 'invoicingAmount',
  // },
  {
    label: '调整天数',
    value: businessData.value?.adjustmentDays || '-',
    key: 'adjustmentDays',
  },
  // {
  //   label: '贴现天数',
  //   value: businessData.value?.discountDays || '-',
  //   key: 'discountDays',
  // },
  {
    label: '年贴现天数',
    value: businessData.value?.annualDiscountDays || '-',
    key: 'annualDiscountDays',
  },
  {
    label: '年贴现率',
    value: businessData.value?.annualDiscountRate ? `${businessData.value.annualDiscountRate}%` : '-',
    key: 'annualDiscountRate',
  },
  {
    label: '贴息费用',
    value: businessData.value?.discountFee ? `￥${businessData.value.discountFee.toLocaleString()}` : '-',
    key: 'discountFee',
  },
  // {
  //   label: '关联金额',
  //   value: businessData.value?.associatedAmount ? `￥${businessData.value.associatedAmount.toLocaleString()}` : '-',
  //   key: 'associatedAmount',
  // },
  {
    label: '贴息承担方',
    value: businessData.value?.discountFeeBearer || '-',
    key: 'discountFeeBearer',
  },
  // {
  //   label: '序列号',
  //   value: businessData.value?.serialNumber || '-',
  //   key: 'serialNumber',
  // },
  // {
  //   label: '业务员',
  //   value: businessData.value?.salesperson || '-',
  //   key: 'salesperson',
  // },
  // {
  //   label: '部门',
  //   value: businessData.value?.department || '-',
  //   key: 'department',
  // },
  // {
  //   label: '机构名称',
  //   value: businessData.value?.institutionName || '-',
  //   key: 'institutionName',
  // },
  // {
  //   label: '部门名称',
  //   value: businessData.value?.departmentName || '-',
  //   key: 'departmentName',
  // },

  {
    label: '备注',
    value: businessData.value?.remarks || '-',
    forceMultiline: true,
    slot: 'remarkSlot',
  },
])

// 准备状态信息数据
const statusInfoList = computed<InfoItem[]>(() => [
  {
    label: '审批状态',
    value: getStatusName('approvalStatus', businessData.value?.approvalStatus || 0) || '-',
    key: 'approvalStatus',
  },
  {
    label: '支付状态',
    value: getStatusText('paymentStatus', businessData.value?.paymentStatus),
    key: 'paymentStatus',
  },
  {
    label: '票据状态',
    value: getStatusText('billStatus', businessData.value?.billStatus),
    key: 'billStatus',
  },
  {
    label: '开票状态',
    value: getStatusText('invoicingStatus', businessData.value?.invoicingStatus),
    key: 'invoicingStatus',
  },
  {
    label: '拆分状态',
    value: getStatusText('splitStatus', businessData.value?.splitStatus),
    key: 'splitStatus',
  },
  {
    label: '是否开票',
    value: getStatusText('isInvoiced', businessData.value?.isInvoiced),
    key: 'isInvoiced',
  },
])

// 准备流程信息数据
const processInfoList = computed<InfoItem[]>(() => [
  {
    label: '流程实例ID',
    value: currentProcess.value?.id || '-',
    key: 'processId',
    forceMultiline: true,
  },
  {
    label: '流程名称',
    value: currentProcess.value?.name || '-',
    key: 'processName',
  },
])
</script>

<template>
  <view class="page">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />
    <!-- 错误提示 -->
    <view v-if="errorMessage" class="error-message">
      <text>{{ errorMessage }}</text>
      <button class="retry-button" @click="getBusinessData()">
        重试
      </button>
    </view>
    <view class="px-4 py-2.5">
      <!-- 汇票信息卡片 -->
      <DetailCard
        title="汇票信息"
        :info-list="billInfoList"
      />
      <!-- 状态信息卡片 -->
      <DetailCard
        title="状态信息"
        :info-list="statusInfoList"
      />

      <!-- 基本信息卡片 -->
      <DetailCard
        title="操作信息"
        :info-list="basicInfoList"
      />

      <!-- 流程信息卡片 -->
      <DetailCard
        title="流程信息"
        :info-list="processInfoList"
      />
    </view>
    <!-- 审批操作栏 -->
    <ApprovalActionBar
      v-if="flowIdValue && currentProcess?.status === 1"
      :process-id="flowIdValue"
    />
  </view>
</template>

<style scoped>
.page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 刷新状态指示器 */
.refresh-indicator {
  background: linear-gradient(to bottom, #fff 0%, #f8f9fa 100%);
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.refresh-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
}

.refresh-spinner {
  width: 32rpx;
  height: 32rpx;
  border: 3rpx solid #e3e3e3;
  border-top: 3rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.refresh-text {
  font-size: 28rpx;
  color: #666;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 错误提示 */
.error-message {
  background-color: #fff2f0;
  border: 1rpx solid #ffccc7;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16rpx;
}

.error-message text {
  color: #ff4d4f;
  font-size: 28rpx;
  flex: 1;
}

.retry-button {
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 6rpx;
  padding: 12rpx 24rpx;
  font-size: 24rpx;
  min-width: 120rpx;
}

.retry-button:active {
  background-color: #d4380d;
}

/* 自定义备注样式 */
.custom-remark {
  display: flex;
  gap: 16rpx;
  background-color: #fff7e6;
  border: 1rpx solid #ffd591;
  border-radius: 8rpx;
  padding: 16rpx;
}

.remark-icon {
  font-size: 32rpx;
  flex-shrink: 0;
}

.remark-content {
  flex: 1;
}

.remark-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  margin-bottom: 8rpx;
}

.remark-note {
  font-size: 24rpx;
  color: #999;
  line-height: 1.4;
  margin-top: 12rpx;
  padding-top: 12rpx;
  border-top: 1rpx solid #ffd591;
}
</style>
